package com.arkopp.partyscanner;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;

public class ConfigActivity extends Activity implements OnClickListener, Runnable {

	private EditText edURL;
	private Spinner spinnerEvents;
	private ScannerConfig sc;
	private ProgressDialog progressDialog;
	private ArrayList<Event> objResponse;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.config);

		Button btnGetEvents = (Button) findViewById(R.id.btnGetEvents);
		Button btnSave = (Button) findViewById(R.id.btnSave);
		btnGetEvents.setOnClickListener(this);
		btnSave.setOnClickListener(this);

		edURL = (EditText) findViewById(R.id.editURL);
		spinnerEvents = (Spinner) findViewById(R.id.spinnerEvents);
		
		sc = ((ScannerConfig)getApplicationContext());
		
		edURL.setText(sc.getCheckInURL());
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
			case R.id.btnGetEvents:
				sc.setCheckInURL(edURL.getText().toString());
				//Get Event List
				progressDialog = ProgressDialog.show(this, "Party Scanner", "Verifying...", true);
				Thread thread = new Thread(this);

				thread.start();
				break;
			case R.id.btnSave:
				sc.setEventID(spinnerEvents.getSelectedItem().toString());
				finish();
				break;
		}
		// TODO Auto-generated method stub

	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		
		String responseBody = "";
		try {


			HttpClient httpclient = new DefaultHttpClient();   
			HttpPost httppost = new HttpPost(edURL.getText().toString() + "/index.php?r=client/getevents"); 
			// Add your data   
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);   

			try {
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				try {
					HttpResponse response = httpclient.execute(httppost);
					responseBody = EntityUtils.toString(response.getEntity());
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}


			ByteArrayInputStream in = new ByteArrayInputStream(responseBody.getBytes());
			InputSource is = new InputSource();
			is.setByteStream(in);


			/* Get a SAXParser from the SAXPArserFactory. */
			SAXParserFactory spf = SAXParserFactory.newInstance();
			SAXParser sp = spf.newSAXParser();

			/* Get the XMLReader of the SAXParser we created. */
			XMLReader xr = sp.getXMLReader();
			/* Create a new ContentHandler and apply it to the XML-Reader*/
			EventXMLHandler xmlhandler = new EventXMLHandler();
			xr.setContentHandler(xmlhandler);

			/* Parse the xml-data from our URL. */
			xr.parse(is);
			/* Our ExampleHandler now provides the parsed data to us. */
			ArrayList<Event> events = xmlhandler.getParsedData();
			objResponse = events;
		} catch (Exception e) {
			e.printStackTrace();
		}
		handler.sendEmptyMessage(0);
		
	}
	
	
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			
			ArrayAdapter<CharSequence> adapter =
					  new ArrayAdapter <CharSequence> (ConfigActivity.this, android.R.layout.simple_spinner_item);
					adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

			Iterator<Event> iterator = objResponse.iterator();
			while(iterator.hasNext()) {
				Log.w("PSCAN",iterator.next().getName());
				adapter.add(iterator.next().getName());
			}
			
			spinnerEvents.setAdapter(adapter);
			
			progressDialog.dismiss();
		}
	};
	
	

}
